const cloud = require('wx-server-sdk')

// 文件格式验证
const SUPPORTED_IMAGE_FORMATS = ['jpg', 'jpeg', 'png', 'pdf']
const SUPPORTED_VIDEO_FORMATS = ['mp4', 'mov', 'avi']
const MAX_VIDEO_SIZE = 200 * 1024 * 1024 // 200MB
const MAX_IMAGE_COUNT = 12

/**
 * 验证图片文件格式
 * @param {string} fileName 文件名
 * @returns {boolean} 是否为支持的格式
 */
function validateImageFormat(fileName) {
  const extension = fileName.split('.').pop().toLowerCase()
  return SUPPORTED_IMAGE_FORMATS.includes(extension)
}

/**
 * 验证视频文件格式
 * @param {string} fileName 文件名
 * @returns {boolean} 是否为支持的格式
 */
function validateVideoFormat(fileName) {
  const extension = fileName.split('.').pop().toLowerCase()
  return SUPPORTED_VIDEO_FORMATS.includes(extension)
}

/**
 * 验证视频文件大小
 * @param {number} fileSize 文件大小（字节）
 * @returns {boolean} 是否在允许范围内
 */
function validateVideoSize(fileSize) {
  return fileSize <= MAX_VIDEO_SIZE
}

/**
 * 验证图片数量
 * @param {number} count 图片数量
 * @returns {boolean} 是否在允许范围内
 */
function validateImageCount(count) {
  return count <= MAX_IMAGE_COUNT
}

/**
 * 生成候选人图片文件路径
 * @param {string} candidateId 候选人ID
 * @param {number} imageIndex 图片索引
 * @param {string} extension 文件扩展名
 * @returns {string} 文件路径
 */
function generateImagePath(candidateId, imageIndex, extension) {
  return `candidates/galleries/${candidateId}_${imageIndex}.${extension}`
}

/**
 * 生成候选人视频文件路径
 * @param {string} candidateId 候选人ID
 * @param {string} extension 文件扩展名
 * @returns {string} 文件路径
 */
function generateVideoPath(candidateId, extension) {
  return `candidates/videos/${candidateId}.${extension}`
}

/**
 * 批量删除云存储文件
 * @param {string[]} fileIds 文件ID数组
 * @returns {Promise<Object>} 删除结果
 */
async function batchDeleteFiles(fileIds) {
  if (!fileIds || !Array.isArray(fileIds) || fileIds.length === 0) {
    return { success: true, deletedCount: 0 }
  }

  try {
    const result = await cloud.deleteFile({
      fileList: fileIds
    })

    const successCount = result.fileList.filter(file => file.status === 0).length
    const failedCount = result.fileList.length - successCount

    return {
      success: failedCount === 0,
      deletedCount: successCount,
      failedCount: failedCount,
      details: result.fileList
    }
  } catch (error) {
    console.error('批量删除文件失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

/**
 * 验证候选人数据
 * @param {Object} candidateData 候选人数据
 * @returns {Object} 验证结果
 */
function validateCandidateData(candidateData) {
  const errors = []

  // 验证必填字段
  if (!candidateData.name || candidateData.name.trim().length === 0) {
    errors.push('候选人姓名不能为空')
  }

  if (!candidateData.activityId) {
    errors.push('活动ID不能为空')
  }

  // 验证姓名长度
  if (candidateData.name && candidateData.name.trim().length > 50) {
    errors.push('候选人姓名不能超过50个字符')
  }

  // 验证图片数量
  if (candidateData.images && candidateData.images.length > MAX_IMAGE_COUNT) {
    errors.push(`图片数量不能超过${MAX_IMAGE_COUNT}张`)
  }

  // 验证额外信息长度
  if (candidateData.extraInfo && candidateData.extraInfo.length > 200) {
    errors.push('额外信息不能超过200个字符')
  }

  return {
    isValid: errors.length === 0,
    errors: errors
  }
}

/**
 * 清理候选人数据
 * @param {Object} candidateData 原始候选人数据
 * @returns {Object} 清理后的数据
 */
function sanitizeCandidateData(candidateData) {
  return {
    name: candidateData.name ? candidateData.name.trim() : '',
    description: candidateData.description ? candidateData.description.trim() : '',
    images: candidateData.images || [],
    videoUrl: candidateData.videoUrl || '',
    videoPoster: candidateData.videoPoster || '',
    audioUrl: candidateData.audioUrl || '',
    extraInfo: candidateData.extraInfo ? candidateData.extraInfo.trim() : '',
    activityId: candidateData.activityId || ''
  }
}

/**
 * 获取文件扩展名
 * @param {string} fileName 文件名
 * @returns {string} 扩展名（小写）
 */
function getFileExtension(fileName) {
  return fileName.split('.').pop().toLowerCase()
}

/**
 * 生成排序权重
 * @param {number} votes 票数
 * @param {Date} createdAt 创建时间
 * @returns {number} 排序权重
 */
function calculateSortWeight(votes, createdAt) {
  // 票数权重占主要因素，创建时间作为次要因素
  const voteWeight = votes * 1000000
  const timeWeight = new Date(createdAt).getTime() / 1000
  return voteWeight + timeWeight
}

module.exports = {
  validateImageFormat,
  validateVideoFormat,
  validateVideoSize,
  validateImageCount,
  generateImagePath,
  generateVideoPath,
  batchDeleteFiles,
  validateCandidateData,
  sanitizeCandidateData,
  getFileExtension,
  calculateSortWeight,
  SUPPORTED_IMAGE_FORMATS,
  SUPPORTED_VIDEO_FORMATS,
  MAX_VIDEO_SIZE,
  MAX_IMAGE_COUNT
} 